package com.douyin.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 第三方API解析服务
 */
@Slf4j
@Service
public class ThirdPartyApiService {

    private final HttpClient httpClient;
    private final ObjectMapper objectMapper;
    private static final String API_URL = "https://www.52api.cn/api/video_parse";
    private static final String API_KEY = "YOK2Sm1FTUP8PTouS4haxJW0tA";
    
    // 抖音分享链接提取正则 - 支持更全面的字符集
    private static final Pattern DOUYIN_URL_PATTERN = Pattern.compile(
        "https?://v\\.douyin\\.com/[A-Za-z0-9_-]+/?", 
        Pattern.CASE_INSENSITIVE
    );
    
    // 备用正则 - 如果第一个失败，使用更宽泛的匹配
    private static final Pattern DOUYIN_URL_PATTERN_FALLBACK = Pattern.compile(
        "https?://v\\.douyin\\.com/[^\\s]+/?", 
        Pattern.CASE_INSENSITIVE
    );

    public ThirdPartyApiService() {
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(30))
            .followRedirects(HttpClient.Redirect.NORMAL)
            .build();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 从用户输入的分享文本中提取抖音URL
     */
    public String extractDouyinUrl(String shareText) {
        if (shareText == null || shareText.trim().isEmpty()) {
            return null;
        }

        log.debug("开始提取抖音URL，原始文本: {}", shareText);
        log.debug("使用主正则表达式: {}", DOUYIN_URL_PATTERN.pattern());
        
        // 先尝试主要的正则表达式
        Matcher matcher = DOUYIN_URL_PATTERN.matcher(shareText);
        String url = null;
        
        if (matcher.find()) {
            url = matcher.group();
            log.info("✅ 主正则表达式成功提取抖音URL: {} (从位置 {} 到 {})", url, matcher.start(), matcher.end());
        } else {
            // 如果主正则失败，尝试备用正则
            log.debug("主正则表达式未匹配，尝试备用正则表达式: {}", DOUYIN_URL_PATTERN_FALLBACK.pattern());
            Matcher fallbackMatcher = DOUYIN_URL_PATTERN_FALLBACK.matcher(shareText);
            
            if (fallbackMatcher.find()) {
                url = fallbackMatcher.group();
                log.info("✅ 备用正则表达式成功提取抖音URL: {} (从位置 {} 到 {})", url, fallbackMatcher.start(), fallbackMatcher.end());
                
                // 清理备用匹配的结果，移除可能的尾随字符
                url = cleanExtractedUrl(url);
                log.debug("🧹 清理后的URL: {}", url);
            }
        }
        
        if (url != null) {
            // 确保URL以斜杠结尾（如果原本没有的话）
            if (!url.endsWith("/")) {
                url = url + "/";
                log.debug("🔧 为URL添加结尾斜杠: {}", url);
            }
            return url;
        }
        
        log.warn("❌ 未找到有效的抖音分享链接，检查的文本: [{}]", shareText);
        return null;
    }
    
    /**
     * 清理提取的URL，移除可能的尾随标点符号
     */
    private String cleanExtractedUrl(String url) {
        if (url == null) return null;
        
        // 移除常见的尾随字符（但保留斜杠）
        while (url.length() > 0) {
            char lastChar = url.charAt(url.length() - 1);
            // 如果最后一个字符是标点符号（除了斜杠），则移除
            if (lastChar == '.' || lastChar == ',' || lastChar == '!' || lastChar == '?' || 
                lastChar == ';' || lastChar == ':' || lastChar == ')' || lastChar == ']' || 
                lastChar == '}' || lastChar == '"' || lastChar == '\'' || lastChar == '>' ||
                lastChar == ' ' || lastChar == '\t' || lastChar == '\n' || lastChar == '\r') {
                url = url.substring(0, url.length() - 1);
            } else {
                break;
            }
        }
        
        return url;
    }

    /**
     * 调用第三方API解析视频
     */
    public Map<String, Object> parseVideo(String douyinUrl) {
        long startTime = System.currentTimeMillis();
        log.info("🚀 开始调用第三方API解析: {}", douyinUrl);

        Map<String, Object> result = new HashMap<>();
        
        try {
            // 构建请求URL
            String requestUrl = API_URL + "?key=" + URLEncoder.encode(API_KEY, StandardCharsets.UTF_8) 
                               + "&url=" + URLEncoder.encode(douyinUrl, StandardCharsets.UTF_8);
            
            log.debug("API请求URL: {}", requestUrl);

            // 构建HTTP请求
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(requestUrl))
                .timeout(Duration.ofSeconds(30))
                .header("Content-Type", "application/x-www-form-urlencoded;charset=utf-8")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
                .GET()
                .build();

            // 发送请求
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
            
            log.debug("API响应状态码: {}", response.statusCode());
            log.debug("API响应内容: {}", response.body());

            if (response.statusCode() == 200) {
                // 解析API响应
                String responseBody = response.body();
                
                // 解析第三方API的JSON响应
                Map<String, Object> parsedData = parseThirdPartyApiResponse(responseBody);
                if (parsedData != null) {
                    result.putAll(parsedData);
                    result.put("success", true);
                    result.put("originalUrl", douyinUrl);
                    result.put("apiResponse", responseBody);
                    
                    long elapsed = System.currentTimeMillis() - startTime;
                    log.info("🎉 第三方API解析成功! 耗时: {}ms, 类型: {}", elapsed, result.get("fileType"));
                } else {
                    throw new RuntimeException("解析第三方API响应失败");
                }
                
            } else {
                throw new RuntimeException("API请求失败，状态码: " + response.statusCode());
            }

        } catch (Exception e) {
            long elapsed = System.currentTimeMillis() - startTime;
            log.error("❌ 第三方API解析失败，耗时: {}ms, 错误: {}", elapsed, e.getMessage());
            
            result.put("success", false);
            result.put("error", e.getMessage());
            result.put("originalUrl", douyinUrl);
        }

        return result;
    }

    /**
     * 解析第三方API的JSON响应
     */
    private Map<String, Object> parseThirdPartyApiResponse(String responseBody) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            Map<String, Object> result = new HashMap<>();
            
            // 检查API响应状态
            if (!rootNode.has("code") || rootNode.get("code").asInt() != 200) {
                throw new RuntimeException("第三方API返回错误: " + rootNode.path("msg").asText("未知错误"));
            }
            
            JsonNode dataNode = rootNode.path("data");
            if (dataNode.isMissingNode()) {
                throw new RuntimeException("第三方API响应缺少data字段");
            }
            
            // 提取基础信息
            String workType = dataNode.path("work_type").asText();
            String workTitle = dataNode.path("work_title").asText();
            String workCover = dataNode.path("work_cover").asText();
            JsonNode workUrlNode = dataNode.path("work_url");
            
            log.debug("解析第三方API响应 - 类型: {}, 标题: {}", workType, workTitle);
            
            // 设置基础字段
            result.put("title", workTitle);
            result.put("cover", workCover);
            result.put("author", dataNode.path("work_author").asText(""));
            
            // 根据内容类型处理
            if ("images".equals(workType)) {
                // 图片类型 - work_url是数组
                result.put("fileType", "image");
                List<String> imageUrls = new ArrayList<>();
                
                if (workUrlNode.isArray()) {
                    for (JsonNode imageNode : workUrlNode) {
                        String imageUrl = imageNode.path("url").asText();
                        if (!imageUrl.isEmpty()) {
                            imageUrls.add(imageUrl);
                        }
                    }
                }
                
                result.put("images", imageUrls);
                log.info("✅ 解析到图片集合，共 {} 张图片", imageUrls.size());
                
            } else if ("video".equals(workType)) {
                // 视频类型 - work_url是字符串
                result.put("fileType", "video");
                String videoUrl = workUrlNode.asText();
                result.put("videoUrl", videoUrl);
                
                log.info("✅ 解析到视频，URL: {}", videoUrl);
                
            } else {
                throw new RuntimeException("不支持的内容类型: " + workType);
            }
            
            // 设置解析方法标识
            result.put("parseMethod", "third-party-api");
            
            return result;
            
        } catch (Exception e) {
            log.error("❌ 解析第三方API响应失败: {}", e.getMessage());
            throw new RuntimeException("解析第三方API响应失败: " + e.getMessage(), e);
        }
    }

    /**
     * 完整的解析流程：提取URL + 调用API
     */
    public Map<String, Object> parseFromShareText(String shareText) {
        log.info("📱 开始处理分享文本解析: {}", shareText);
        
        // 1. 提取抖音URL
        String douyinUrl = extractDouyinUrl(shareText);
        if (douyinUrl == null) {
            Map<String, Object> errorResult = new HashMap<>();
            errorResult.put("success", false);
            errorResult.put("error", "未找到有效的抖音分享链接");
            errorResult.put("originalText", shareText);
            return errorResult;
        }

        // 2. 调用第三方API解析
        Map<String, Object> result = parseVideo(douyinUrl);
        result.put("originalText", shareText);
        result.put("extractedUrl", douyinUrl);
        
        return result;
    }
}